<template>
  <div>
    <div style="margin-bottom:10px">
      <search-form
        :search-config="searchConfig"
        :label-width="100"
        @clear="clearSearch"
        @search="handleSearch"
      />
    </div>
    <el-table
      v-loading="tableLoading"
      :data="tableData"
      style="width: 100%"
      header-row-class-name="table-list-header"
      highlight-current-row
      border
      :span-method="objectSpanMethod"
    >
      <el-table-column type="index" label="序号" width="50" />
      <el-table-column label="所属区域" prop="areaName" min-width="80" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.areaName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属空间" prop="spaceName" show-overflow-tooltip min-width="80" />
      <el-table-column label="是否报图" prop="isReport" min-width="80" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ formaterData(booleansLists, scope.row.isReport) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="空间报图面积" prop="spaceReportArea" show-overflow-tooltip min-width="100" />
      <el-table-column label="空间是否出图" prop="isOutpic" show-overflow-tooltip min-width="100">
        <template slot-scope="scope">
          <span>{{ formaterData(booleansLists, scope.row.isOutpic) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="空间出图面积" prop="outpicArea" show-overflow-tooltip min-width="100" />
      <!-- <el-table-column label="空间出图说明" prop="outpicDesc" show-overflow-tooltip min-width="180" /> -->
      <el-table-column label="空间验收面积" prop="acceptArea" show-overflow-tooltip min-width="100" />
      <!-- <el-table-column label="空间验收说明" prop="spaceAcceptDesc" show-overflow-tooltip min-width="180" /> -->
      <el-table-column label="所属专区" prop="styleName" show-overflow-tooltip min-width="90" />
      <el-table-column label="专区报图面积" prop="styleReportArea" show-overflow-tooltip min-width="110" />
      <el-table-column label="专区出图面积" prop="styleActualOutpicArea" show-overflow-tooltip min-width="110" />
      <!-- <el-table-column label="专区出图说明" prop="styleOutDesc" show-overflow-tooltip min-width="110" /> -->
      <el-table-column label="专区验收面积" prop="acceptDetailArea" show-overflow-tooltip min-width="120" />
      <!-- <el-table-column label="专区验收说明" prop="styleAcceptDesc" show-overflow-tooltip min-width="120" /> -->
      <el-table-column label="配套定制出图面积" prop="assortCustomizedSeriesOutArea" show-overflow-tooltip min-width="120" />
      <el-table-column label="配套定制验收面积" prop="assortCustomizedSeriesAcceptArea" show-overflow-tooltip min-width="120" />
      <el-table-column label="产品系列" prop="seriesName" show-overflow-tooltip min-width="80" />
      <el-table-column label="系列报图面积" prop="seriesReportArea" show-overflow-tooltip min-width="100" />
      <el-table-column label="配套定制系列" prop="chooseCustomizedSeriesName" show-overflow-tooltip min-width="100" />
      <el-table-column label="配套橱柜系列" prop="chooseCupboardSeriesName" show-overflow-tooltip min-width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.chooseCupboardSeriesName || scope.row.assortCupboardSeriesName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="所属空间" prop="spaceName" show-overflow-tooltip min-width="80" /> -->
      <el-table-column label="是否报图" prop="isSeriesReportPic" min-width="80" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ formaterData(booleansList, scope.row.isSeriesReportPic) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否出图" prop="isOutpicDetail" min-width="80" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ formaterData(booleansLists, scope.row.isOutpicDetail) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否验收" prop="isAccept" min-width="80" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ formaterData(booleansLists, scope.row.isAccept) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="系列出图面积" prop="seriesOutpicArea" min-width="100" />
      <el-table-column label="配套定制面积" prop="assortCustomizedArea" min-width="100" />
      <el-table-column label="实际验收面积" prop="acceptSeriesArea" min-width="100" /> -->
    </el-table>
    <div class="pagination-box">
      <div class="pagination-container">
        <el-pagination
          :current-page.sync="currentPage"
          :page-sizes="pageSizelist"
          :page-size="pageSize"
          layout="sizes, prev, pager, next, slot"
          :total="allTotal === 0 ? total : allTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
          <span class="el-pagination__jump">前往
            <el-input-number
              v-model="jumpPage"
              :controls="false"
              :min="1"
              @blur="showEnter"
              @keyup.enter.native="showEnter"
            />页</span>
        </el-pagination>
        <div v-show="total <= pageSize" class="pagination-info">当前显示
          <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
          <span class="total"> {{ tableData.length }} </span> 条记录
        </div>
        <div v-show="total > pageSize" class="pagination-info">当前显示
          <span>{{ handlePageRange(pageSize, currentPage) }}</span>，共
          <span :class="[allTotal === 0 && total !== 0 ? 'total next-page': 'total']" @click="newEnter"> {{ allTotal === 0 && total !== 0 ? total-1 +'+': allTotal }}  </span> 条记录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { queryAreaSeriesData } from '@/api/storeConstruction'
import { getDictByPatchType } from '@/api/dataDict'
export default {
  name: 'AreaSeriesTable',
  props: {
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      belongRegionList: [
        { dictName: '套房', dictCode: 'Q015' },
        { dictName: '全屋定制', dictCode: 'Q002' },
        { dictName: '整体橱柜', dictCode: 'Q003' },
        { dictName: '卫浴', dictCode: 'Q004' },
        { dictName: '样板间', dictCode: 'Q005' },
        { dictName: '软体', dictCode: 'Q014' },
        { dictName: '情景间', dictCode: 'Q019' }
      ],
      suitDesignWayList: [],
      booleansList: [],
      booleansLists: [
        { dictName: '是', dictCode: 1 },
        { dictName: '否', dictCode: 0 }
      ],
      searchConfig: [
        {
          label: '所属区域',
          prop: 'areaCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post', // 远程搜索请求方式
            remoteUrl: `${process.env.VUE_APP_BASE_API}/api/v1/configArea/page`, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'areaName', // productSaleSeriesName
              value: 'areaCode' // code
            }, // api返回数据默认字段
            multiple: false
          },
          dialogConfig: {
            title: '所属区域',
            interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configArea/page`,
            setting: [
              { prop: 'areaCode', title: '编码' },
              { prop: 'areaName', title: '名称' }
            ]
          }
        },
        {
          label: '所属空间',
          prop: 'spaceCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post', // 远程搜索请求方式
            remoteUrl: `${process.env.VUE_APP_BASE_API}/api/v1/configSpace/page`, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'spaceName', // productSaleSeriesName
              value: 'spaceCode' // code
            }, // api返回数据默认字段
            multiple: false
          },
          dialogConfig: {
            title: '所属空间',
            interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configSpace/page`,
            setting: [
              { prop: 'spaceCode', title: '编码' },
              { prop: 'spaceName', title: '名称' }
            ]
          }
        },
        {
          label: '所属专区',
          prop: 'styleCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post', // 远程搜索请求方式
            remoteUrl: `${process.env.VUE_APP_BASE_API}/api/v1/configStyle/page`, // 远程搜索API地址
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'styleName', // productSaleSeriesName
              value: 'styleCode' // code
            }, // api返回数据默认字段
            multiple: false
          },
          dialogConfig: {
            title: '所属专区',
            interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configStyle/page`,
            setting: [
              { prop: 'styleCode', title: '编码' },
              { prop: 'styleName', title: '名称' }
            ]
          }
        },
        { label: '系列名称', prop: 'seriesName', type: 'text', value: '', placeholder: '', single: true }
      ],
      tableLoading: false,
      tableData: [],
      otherFilters: [],
      pageSize: 10,
      pageSizelist: [10, 20, 30, 50, 100],
      currentPage: 1,
      total: '',
      jumpPage: '',
      allTotal: 0,
      constCode: ''
    }
  },
  computed: {},
  async created() {
    await this.getDictByTypeCode(['SUIT_DESIGN_WAY', 'BOOLEANS']).then(res => {
      this.suitDesignWayList = res.SUIT_DESIGN_WAY
      this.booleansList = res.BOOLEANS
    })
    this.constCode = this.detailData.constCode
    this.getTableData(1, 10, false, this.otherFilters)
  },
  activated() {},
  methods: {
    // 获取数据字典
    async getDictByTypeCode(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      if (!arr || !arr.length) return
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    // 多选数据格式化
    formaterArr(data, str) {
      if (!data || !data.length || !str || !str.length) return
      let list = []
      if (typeof (str) === 'string') {
        list = str.split(',')
      } else {
        list = str
      }
      const arr = []
      data.forEach((item) => {
        const flag = list.some(v => v === item.dictCode)
        if (flag) {
          arr.push(item.dictName)
        }
      })
      return arr.toString()
    },
    // 合并表格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        return {
          rowspan: row.areaSpanRow,
          colspan: row.areaSpanColumn
        }
      } else if (columnIndex >= 2 && columnIndex <= 7) {
        return {
          rowspan: row.programSpanRow,
          colspan: row.programSpanColumn
        }
      } else if (columnIndex >= 8 && columnIndex <= 13) {
        return {
          rowspan: row.styleSpanRow,
          colspan: row.styleSpanColumn
        }
      }
      return {
        rowspan: 1,
        colspan: 1
      }
    },
    // 处理数据
    handlerData(data) {
      const t = {}
      for (const item of data) {
        const key = item.areaCode
        if (t[key] === undefined) {
          t[key] = []
        }
        t[key].push(item)
      }
      // 按照区域合并
      const result = []
      for (const [k, v] of Object.entries(t)) {
        const programs = {}
        for (let i = 0; i < v.length; i++) {
          const item = v[i]
          if (i === 0) {
            item.areaSpanRow = v.length
            item.areaSpanColumn = 1
          } else {
            item.areaSpanRow = 0
            item.areaSpanColumn = 0
          }
          const key = item.spaceCode || item.spaceName
          if (programs[key] === undefined) {
            programs[key] = []
          }
          programs[key].push(item)
        }
        // 按照方案合并
        // eslint-disable-next-line no-unused-vars
        for (const [k, v] of Object.entries(programs)) {
          const obj = {}
          v.forEach((e, i) => {
            if (i === 0) {
              e.programSpanRow = v.length
              e.programSpanColumn = 1
            } else {
              e.programSpanRow = 0
              e.programSpanColumn = 0
            }
            const key = e.styleCode || e.styleName
            if (obj[key] === undefined) {
              obj[key] = []
            }
            obj[key].push(e)
          })
          for (const [I, item] of Object.entries(obj)) {
            item.forEach((e, i) => {
              if (i === 0) {
                e.styleSpanRow = item.length
                e.styleSpanColumn = 1
              } else {
                e.styleSpanRow = 0
                e.styleSpanColumn = 0
              }
              e.group = item
              result.push(e)
            })
          }
        }
      }
      return result
    },

    // 获取表格数据
    getTableData(page, rows, onlyCountFlag, otherFilters) {
      this.tableLoading = true
      const arr = [{ 'id': 'constCode', 'property': 'constCode', 'operator': '=', 'value': this.constCode },
        { 'id': 'dr', 'property': 'dr', 'operator': '=', 'value': 0 }]
      const sortersRow = []
      const form = new FormData()
      form.append('page', page)
      form.append('rows', rows)
      form.append('sort', '')
      form.append('order', 'desc')
      form.append('pageFlag', true)
      form.append('onlyCountFlag', onlyCountFlag)
      form.append('filtersRaw', JSON.stringify([...otherFilters, ...arr]))
      form.append('sortersRaw', JSON.stringify(sortersRow))
      form.append('paramsRaw', JSON.stringify({}))
      queryAreaSeriesData(form).then(res => {
        if (res.success && res.data && res.data.records) {
          if (!onlyCountFlag) {
            this.tableData = this.handlerData(res.data.records || [])
            this.total = res.data.total
            if (res.data.total <= this.currentPage * this.pageSize) {
              this.allTotal = this.total
            } else {
              this.allTotal = 0
            }
          } else {
            this.allTotal = res.data.total
            this.total = res.data.total
            this.currentPage = res.data.page
          }
        }
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 去重
    unique(arr, flag) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr[flag]) && res.set(arr[flag], 1))
    },
    // 前往第几页
    showEnter(ev) {
      this.jumpPage = ev.srcElement.value
      this.getTotal(this.jumpPage)
    },
    // 获取总数据条数
    newEnter() {
      this.getTotal(this.currentPage)
    },
    // 当操作在非第一页时，跳回第一页
    jumpToFirstPage() {
      this.currentPage = 1 // 不在第一页搜索时，调回第一页显示
      this.jumpPage = 1
      this.allTotal = 0
      this.total = 0
    },
    // 分页，获取下一页数据
    handleCurrentChange(currentPage) {
      this.jumpPage = currentPage
      this.currentPage = currentPage
      this.getTableData(this.currentPage, this.pageSize, false, this.otherFilters)
    },
    // 分页数据获取---> this.$refs.chosenTable/multipleTable.clearSelection
    handleSizeChange(val) {
      this.pageSize = val
      this.jumpToFirstPage()
      this.getTableData(this.currentPage, this.pageSize, false, this.otherFilters)
    },
    // 计算当前数据范围 如:1-20
    handlePageRange(size, currentPage) {
      const start = size * (currentPage - 1) + 1
      const end = size * currentPage
      const pageRange = `${start}-${end}`
      return pageRange
    },
    // 获取数据总条数
    getTotal(val) {
      if (this.allTotal !== 0) return
      let page = this.currentPage
      if (val) {
        page = val
      }
      this.getTableData(page, this.pageSize, true, this.otherFilters)
      // this.$nextTick(() => {
      //   this.getTableData(page, this.pageSize, false, this.otherFilters)
      // })
    },
    // 搜索
    handleSearch(data) {
      this.otherFilters = []
      if (data && data.filtersRaw) {
        this.otherFilters = [...data.filtersRaw]
      }
      this.getTableData(1, this.pageSize, false, this.otherFilters)
    },
    // 清空搜索
    clearSearch() {
      this.otherFilters = []
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
